<template>
    <div>
        <!-- 头部面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片布局 -->
        <el-card>
            <el-row>
                <el-col>
                   <!-- 添加角色的按钮 -->
                   <el-button type="primary" @click="showAddRles()">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表 -->
            <el-table :data="rolesList" style="width: 100%" stripe border>
                <!-- 展开列  -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 权限展示 -->
                        <el-row :class="[i1 === 0 ? '' : 'bdtop', 'vcenter']" v-for="( item, i1) in scope.row.children" :key="item.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                              <el-tag closable @close = "removeRightById(scope.row, item.id)"> {{ item.authName }} </el-tag>
                              <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二、三级权限 -->
                            <el-col :span="19">
                               <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter' ]" v-for="( item1, i2) in item.children" :key="item1.id">
                                 <!-- 二级权限 -->
                                 <el-col :span="6">
                                    <el-tag type="success" closable @close = "removeRightById(scope.row, item1.id)"> {{ item1.authName }} </el-tag>
                                    <i class="el-icon-caret-right"></i>
                                 </el-col>
                                 <!-- 三级权限 -->
                                 <el-col :span="18">
                                    <el-tag type="warning" v-for="(item2) in item1.children" :key="item2.id" closable @close = "removeRightById(scope.row, item2.id)"> {{ item2.authName }} </el-tag>
                                 </el-col>
                               </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列  -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="200px">
                    <template slot-scope="scope">
                        <!-- 修改角色 -->
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="updataRole(scope.row.id)"></el-button>
                        <!-- 删除角色 -->
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)"></el-button>
                        <!-- 分配权限  -->
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetVisibleDialog(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色对话框  -->
        <el-dialog
          title="添加角色"
          :visible.sync=" addRolesVisible"
          width="50%">
          <!-- 内容区域 -->
            <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
              <el-form-item label="角色名称"  prop='roleName'>
                <el-input v-model="addRolesForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述"  prop='roleDesc'>
                <el-input v-model="addRolesForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>
          <!-- 底部区域 -->
          <span slot="footer">
            <el-button @click="addRolesVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole()">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 编辑角色对话框 -->
        <el-dialog
            title="编辑角色"
            :visible.sync="updataRoleVisible"
            width="50%">
             <!-- 内容区 -->
            <el-form :model="updataRoleForm" :rules="updataRoleRules" ref="updataFormRef" label-width="80px">
              <el-form-item label="角色名" disabled>
                <el-input v-model="updataRoleForm.roleName" disabled></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="updataRoleForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="updataRoleVisible = false">取 消</el-button>
              <el-button type="primary" @click="updateRoleSubmit()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限对话框 -->
        <el-dialog
          title="分配权限"
          :visible.sync="SetVisibleDialog"
          width="50%">
          <!-- 内容区域 -->
          <!-- 分配权限的树形控件  -->
          <el-tree :data="rightslist" :props="roleProps" show-checkbox :default-checked-keys = 'defaultCheckedkeys' node-key='id' ref = treeRef></el-tree>
          <!-- 底部区域 -->
          <span slot="footer">
            <el-button @click="SetVisibleDialog = false">取 消</el-button>
            <el-button type="primary" @click="allowRights()">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
    //   存放角色列表数据
      rolesList: [],
      addRolesVisible: false,
      //  添加角色表单数据对象
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //   添加角色校验规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      //   编辑角色对话框
      updataRoleVisible: false,
      //   编辑角色对话框的表单数据
      updataRoleForm: {
        roleName: '',
        roleDesc: '',
        roleId: 0
      },
      updataRoleRules: {
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限对话框
      SetVisibleDialog: false,
      // 所有的权限列表数据
      rightslist: [],
      // 树形控件props的条件
      roleProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认选中的项
      defaultCheckedkeys: [],
      // 当前点击的角色ID值
      roleId: 0
    }
  },
  created() {
    // 调用获取角色列表数据函数
    this.getRolesList()
  },
  methods: {
    //  获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表数据失败')
      this.rolesList = res.data
    },
    showAddRles() {
      this.addRolesVisible = true
    },
    // 添加角色
    addRole() {
      //    先进行预验证
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return
        // 请求角色的添加
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addRolesVisible = false
        this.getRolesList()
      })
    },
    // 编辑角色
    async updataRole(id) {
      this.updataRoleVisible = true
      // 根据传过来的ID查询角色
      const { data: res } = await this.$http.get(`roles/${id}`)
      this.updataRoleForm = res.data
    },
    // 编辑角色数据提交
    updateRoleSubmit() {
      // 进行表单预验证
      this.$refs.updataFormRef.validate(async valid => {
        if (!valid) return
        //   获取修改结果
        const { data: res } = await this.$http.put(`roles/${this.updataRoleForm.roleId}`, {
          roleName: this.updataRoleForm.roleName,
          roleDesc: this.updataRoleForm.roleDesc
        }
        )
        console.log(this.updataRoleForm.roleId)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        this.$message.success('修改用户信息成功')
        // 调用获取角色列表函数
        this.getRolesList()
        // 隐藏对话框
        this.updataRoleVisible = false
      })
    },
    // 删除角色功能
    async deleteRole(id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 删除用户
      this.$http.delete(`roles/${id}`).then(res => {
        console.log(res)
        const { data } = res
        if (data.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getRolesList()
      })
    },
    // 根据ID删除用户权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      role.children = res.data
    },
    // 获取权限数据
    async showSetVisibleDialog(role) {
      // 清空显示选中的数组
      this.defaultCheckedkeys = []
      // 设置对话框显示
      this.SetVisibleDialog = true

      // 获取权限树型结构
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) return this.$message.error('获取权限列表数据失败')
      this.rightslist = res.data

      // 给roleID赋值为当前点击的角色的ID
      this.roleId = role.id

      // 调用获取三级权限ID值的函数
      this.getRightsListID(role, this.defaultCheckedkeys)

      console.log(this.rolesList)
    },
    // 通过递归把三级权限ID值赋给data里面
    getRightsListID(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      // forEach 对所有孩子的三级权限的ID进行收集
      node.children.forEach(item => {
        this.getRightsListID(item, arr)
      })
    },
    // 获取选中的权限列表并添加
    async allowRights() {
      // 获取选中和半选中的ID数组
      const defkeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      // 把数组变为字符串
      const degkeysString = defkeys.join(',')

      // 请求接口 添加权限
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: degkeysString })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.SetVisibleDialog = false
      this.getRolesList()
    }
  }
}

</script>

<style lang="less">
  .el-tag {
    margin-top: 7px;
    margin-left: 10px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
